class StoryController < ApplicationController
  def index
    list
    render :action => 'list'
  end

  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :destroy, :create, :update ],
         :redirect_to => { :action => :list }

  def list
    @story_pages, @stories = paginate :stories, :per_page => 10
  end

  def show
    @story = Story.find(params[:id])
  end

  def new
  end

  def create
    tuples = []
    title = params[:story][:title]
    text_tuples = params[:story][:tuples].split

    text_tuples.each do |it|
      text_tuple = it.split ":"
      if text_tuple.length == 1 then
        group = nil
        tag = Tag.find_or_create_by_name text_tuple[0]
      else
        group = Group.find_or_create_by_name text_tuple[0]
        tag = Tag.find_or_create_by_name text_tuple[1]
      end
      tuples.push Tuple.find_or_create_by_group_and_tag(group, tag)
    end
    
    @story = Story.new
    @story.title = params[:story][:title]
    @story.tuples = tuples
    if @story.save
      flash[:notice] = 'Story was successfully created.'
      redirect_to :action => 'list'
    else
      render :action => 'new'
    end
  end

  def edit
    @story = Story.find(params[:id])
  end

  def update
    @story = Story.find(params[:id])
    if @story.update_attributes(params[:story])
      flash[:notice] = 'Story was successfully updated.'
      redirect_to :action => 'show', :id => @story
    else
      render :action => 'edit'
    end
  end

  def destroy
    Story.find(params[:id]).destroy
    redirect_to :action => 'list'
  end
end
